<template>
  <div class="upload">
    <input type="file" @change="importFile">
    <span>{{progress}}</span>
    <button @click="cancel">取消</button>
  </div>
</template>

<script>
export default {
  name: 'upload',
  data() {
    return {
      progress: '0%',
      source: null
    }
  },
  mounted() {
    window.onunload = (a, b, c) => {
      alert('欢迎下次再来')
    }
    window.onbeforeunload = (e) => {
      e.returnValue = '确定离开当前页面吗？';
    }
  },
  methods: {
    // 上传文件
    importFile(e) {
      let file = e.target.files[0]
      let formdata = new FormData()
      formdata.append('file', file)
      this.source = this.$axios.CancelToken.source()
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/uploadhistory/uploadHistory/upload',
        data: formdata,
        onUploadProgress: this.progressBar,
        cancelToken: this.source.token
      })
    },
    // 上传进度回调
    progressBar(progressEvent) {
      if (progressEvent.lengthComputable) {
        this.progress = parseInt(progressEvent.loaded / progressEvent.total * 100) + '%'
      }
    },
    cancel() {
      this.source.cancel('终止请求')
    }
  }
}
</script>

<style scoped lang="less">

</style>
